package com.ms.core.service.admin.service.impl;

import com.ms.base.jdbc.dao.IBaseDao;
import com.ms.base.jdbc.service.BaseServiceImpl;
import com.ms.core.comm.admin.dto.SaveBatchAdminMenuRequest;
import com.ms.core.comm.admin.model.AdminMenuModel;
import com.ms.core.service.admin.dao.IAdminMenuDao;
import com.ms.core.service.admin.service.IAdminMenuService;
import com.ms.core.service.admin.service.IAdminRoleMenuService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/**
 * <b>description</b>：后台菜单表业务实现类 <br>
 * <b>time</b>：2018-08-21 09:15:21 <br>
 * <b>author</b>：ready likun_557@163.com
 */
@Service
public class AdminMenuServiceImpl extends BaseServiceImpl<java.lang.Long, AdminMenuModel> implements IAdminMenuService {
    @Autowired
    private IAdminMenuDao adminMenuDao;
    @Autowired
    private IAdminRoleMenuService adminRoleMenuService;

    @Override
    public IBaseDao<java.lang.Long, AdminMenuModel> getBaseDao() {
        return this.adminMenuDao;
    }

    @Override
    public AdminMenuModel insert(AdminMenuModel model) throws Exception {
        Assert.notNull(model, "model is not null!");
        Assert.isTrue(StringUtils.isNotBlank(model.getName()), "名称不能为空!");
        Assert.isTrue(model.getPid() == null || model.getPid() == 0L || StringUtils.isNotBlank(model.getUrl()), "url不能为空!");
        return super.insert(model);
    }

    @Override
    public int update(AdminMenuModel model) throws Exception {
        Assert.notNull(model, "model is not null!");
        Assert.isTrue(StringUtils.isNotBlank(model.getName()), "名称不能为空!");
        Assert.isTrue(model.getPid() == null || model.getPid() == 0L || StringUtils.isNotBlank(model.getUrl()), "url不能为空!");
        return super.update(model);
    }

    @Override
    @Transactional
    public void saveBatch(SaveBatchAdminMenuRequest dto) throws Exception {
        Assert.notNull(dto, "dto is not null!");
        if (dto.getAdminMenuModels() != null && !dto.getAdminMenuModels().isEmpty()) {
            List<AdminMenuModel> adminMenuModels = dto.getAdminMenuModels();
            for (AdminMenuModel model : adminMenuModels) {
                if (model.getId() != null) {
                    Assert.isTrue(StringUtils.isNotBlank(model.getName()), "名称不能为空!");
                    Assert.isTrue(model.getPid() == null || model.getPid() == 0L || StringUtils.isNotBlank(model.getUrl()), "url不能为空!");
                    this.adminMenuDao.update(model);
                }
            }
        }
    }

    @Override
    public int deleteById(Long id) throws Exception {
        this.adminRoleMenuService.deleteByMenuId(id);
        return super.deleteById(id);
    }
}